import React, { useState, useEffect } from "react";
import { Card, List, Tag, Spin, Tabs, Alert, Pagination, Input } from "antd";
import {
  NotificationOutlined,
  RedditOutlined,
  BankOutlined,
  GlobalOutlined,
  SearchOutlined,
  TagsOutlined,
} from "@ant-design/icons";
import { $fetchFinanceNews } from "../../api/newsApi";
import "./News.scss";

const { TabPane } = Tabs;
const { Search } = Input;

const newsSources = [
  { key: "all", name: "全部", icon: <GlobalOutlined />, color: "purple" },
  { key: "sina", name: "新浪财经", icon: <RedditOutlined />, color: "red" },
  {
    key: "xueqiu",
    name: "雪球",
    icon: <NotificationOutlined />,
    color: "green",
  },
  { key: "pbc", name: "央行", icon: <BankOutlined />, color: "blue" },
];

const News = () => {
  const [loading, setLoading] = useState(true);
  const [newsData, setNewsData] = useState([]);
  const [activeSource, setActiveSource] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const [searchText, setSearchText] = useState("");
  const [error, setError] = useState(null);
  const pageSize = 10;

  useEffect(() => {
    const fetchNews = async () => {
      try {
        setLoading(true);
        const res = await $fetchFinanceNews({
          source: activeSource,
          page: currentPage,
          limit: pageSize,
          search: searchText,
        });

        if (res.code === 0) {
          setNewsData(res.data);
          setTotalItems(res.data.length); // 根据实际返回结构调整
        } else {
          throw new Error(res.message || "获取新闻失败");
        }
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    fetchNews();
  }, [activeSource, currentPage, searchText]);

  const handleSearch = (value) => {
    setSearchText(value);
    setCurrentPage(1);
  };

  const filteredData = newsData.filter(
    (item) =>
      item.title.includes(searchText) ||
      (item.content && item.content.includes(searchText))
  );

  // 格式化时间显示
  const formatTime = (timeStr) => {
    return new Date(timeStr).toLocaleString();
  };

  // 渲染标签
  const renderTags = (tags) => {
    if (!tags || !Array.isArray(tags)) return null;

    return (
      <div style={{ marginTop: 8 }}>
        <TagsOutlined style={{ marginRight: 4 }} />
        {tags.map((tag, index) => (
          <Tag key={index}>{tag}</Tag>
        ))}
      </div>
    );
  };

  return (
    <div className="news-page">
      <Card
        title="财经新闻资讯"
        bordered={false}
        extra={
          <Search
            placeholder="搜索新闻标题或内容"
            allowClear
            enterButton={<SearchOutlined />}
            size="large"
            onSearch={handleSearch}
            style={{ width: 300 }}
          />
        }
      >
        {error && <Alert message={error} type="error" showIcon />}

        <Tabs
          activeKey={activeSource}
          onChange={setActiveSource}
          tabBarStyle={{ marginBottom: 20 }}
        >
          {newsSources.map((source) => (
            <TabPane
              tab={
                <Tag color={source.color}>
                  {source.icon} {source.name}
                </Tag>
              }
              key={source.key}
            >
              <Spin spinning={loading}>
                <List
                  itemLayout="vertical"
                  size="large"
                  dataSource={filteredData}
                  renderItem={(item) => (
                    <List.Item
                      key={item.id}
                      actions={[
                        <span>{formatTime(item.update_time)}</span>,
                        <a
                          href={item.link}
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          查看原文
                        </a>,
                      ]}
                    >
                      <List.Item.Meta
                        title={<a href={item.link}>{item.title}</a>}
                        description={
                          <Tag
                            color={
                              newsSources.find((s) => s.key === "sina")
                                ?.color || "gray"
                            }
                          >
                            {newsSources.find((s) => s.key === "sina")?.name ||
                              "未知来源"}
                          </Tag>
                        }
                      />
                      {renderTags(item.tags)}
                    </List.Item>
                  )}
                />
                <div style={{ textAlign: "center", marginTop: 20 }}>
                  <Pagination
                    current={currentPage}
                    total={totalItems}
                    pageSize={pageSize}
                    onChange={(page) => setCurrentPage(page)}
                    showSizeChanger={false}
                  />
                </div>
              </Spin>
            </TabPane>
          ))}
        </Tabs>
      </Card>
    </div>
  );
};

export default News;
